import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '../store'

// import Reg from '@/views/reg/Reg.vue'
const Reg = () => import('@/views/reg/Reg.vue')
// import Login from '@/views/login/login.vue'
const Login = () => import('@/views/login/login.vue')
// import Main from '@/views/main/main.vue'
const Main = () => import('@/views/main/main.vue')

// import Home from '@/views/menus/home/home.vue'
const Home = () => import('@/views/menus/home/home.vue')

// import UserInfo from '@/views/menus/user/userInfo.vue'
const UserInfo = () => import('@/views/menus/user/userInfo.vue')

// import UserAvatar from '@/views/menus/user/userAvatar.vue'
const UserAvatar = () => import('@/views/menus/user/userAvatar.vue')

// import UserPwd from '@/views/menus/user/userPwd.vue'
const UserPwd = () => import('@/views/menus/user/userPwd.vue')

// import ArtCate from '@/views/Article/artCate.vue'
const ArtCate = () => import('@/views/Article/artCate.vue')

// import ArtList from '@/views/Article/artList.vue'
const ArtList = () => import('@/views/Article/artList.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  { path: '/reg', component: Reg },
  { path: '/login', component: Login },
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: ArtList }
    ]
  }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    if (store.state.token) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
